﻿using Kerberos.NET.Client;
using Kerberos.NET.Configuration;
using Kerberos.NET.Credentials;
using Kerberos.NET.Crypto;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using System.Net.Http.Headers;
using System.Text;
using Utils;
using Xunit.Abstractions;

namespace CSharpDemos
{
    public class KerberosValidator
    {
        ILogger _logger;
        ILoggerFactory _loggerFactory;

        public KerberosValidator(ITestOutputHelper? output)
        {
            _loggerFactory = LoggerFactory.Create(builder =>
            {
                builder
                    .AddFilter("Microsoft", LogLevel.Warning)
                    .AddFilter("System", LogLevel.Warning)
                    .AddFilter("RestNegotiateClient.Program", LogLevel.Debug)
                    .AddFilter("Kerberos.Net", LogLevel.Trace)
                    .AddConsole(delegate (ConsoleLoggerOptions d) { });
            });
            if (output != null)
            {
                _loggerFactory.AddProvider(new XunitLoggerProvider(output));
            }
            _logger = _loggerFactory.CreateLogger<KerberosValidator>();
        }

        public async Task Test()
        {
            try
            {
                var keytab = new KeyTable(File.ReadAllBytes("files/user.keytab"));
                var kerbCred = new KeytabCredential("washout@HADOOP.COM", keytab);

                var krb5 = Encoding.ASCII.GetString(File.ReadAllBytes("files/krb5.conf"));
                var list = Krb5ConfigurationSerializer.Deserialize(krb5);
                var client = new KerberosClient(list.ToConfigObject(), _loggerFactory);

                _logger.LogInformation("开始");

                await client.Authenticate(kerbCred);

                _logger.LogInformation("成功");

                var ticket = await client.GetServiceTicket("HOST/34.8.8.215");

                string header = Convert.ToBase64String(ticket.EncodeGssApi().ToArray());
                _logger.LogInformation($"header=" + header);
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Negotiate", header);

                //todo:HTTP请求
            }
            catch (Exception ex)
            {
                _logger.LogError($"{ex}");
            }
        }
    }
}
